/*******************************************************************************
 * 1. 数量：H_AMOUNT 2.折扣：H_DISCOUNT 3.定价：H_PRICE 4.单品实价：H_PRICE_REAL
 * （进货单为成本价，销售单为销价） 5.不含税单品实价：H_PRICE_REAL_NOTAX 6 实洋：REAL_MONEY_ITEM
 * 7.码洋：TOTAL_MONEY_ITEM
 * 
 * 需要实现的计算公式有以下： 1.H_PRICE_REAL=H_PRICE*H_DISCOUNT(当 填写了折扣后，回车 或 焦点移开 触发计算)
 * 2.H_DISCOUNT=H_PRICE_REAL / H_PRICE（当 直接填写 单品实价后，回车 或焦点移开 触发计算）
 * 3.实洋=H_PRICE_REAL*H_AMOUNT（当 单品实价计算出来以后，自动触发计算） 4.码洋=H_PRICE*H_AMOUNT(当 数量填写
 * 回车或焦点移开 自动触发计算) 5.单品不含税价:H_PRICE_REAL_NOTAX=H_PRICE_REAL/(1+TAX_RATE)
 * (批销单可能不引用该列，后期可能发生变化)
 */
var fixno = 2;
function totalcalcu(prefix, oldlength, newlength) {
	var allRows = $('#' + prefix + "_addItemDatagrid").datagrid('getRows');
	for ( var i = oldlength; i < newlength; i++) {
		if (allRows[i]["H_AMOUNT"] == undefined || allRows[i]["H_AMOUNT"] == '') {
			allRows[i]["H_AMOUNT"] = 0;
		}
		if (allRows[i]["H_PRICE"] == undefined || allRows[i]["H_PRICE"] == '') {
			allRows[i]["H_PRICE"] = 0;
		}
		if (allRows[i]["H_DISCOUNT"] == undefined
				|| allRows[i]["H_DISCOUNT"] == '') {
			allRows[i]["H_DISCOUNT"] = 0;
		}
		allRows[i]["TOTAL_MONEY_ITEM"] = (parseFloat(allRows[i]["H_AMOUNT"]
				* allRows[i]["H_PRICE"])).toFixed(fixno); // 码洋
		allRows[i]["REAL_MONEY_ITEM"] = (parseFloat(allRows[i]["H_AMOUNT"]
				* allRows[i]["H_PRICE"] * allRows[i]["H_DISCOUNT"]))
				.toFixed(fixno); // 实洋
		if (allRows[i]["TAX_RATE"] != undefined
				&& allRows[i]["TAX_RATE"] != null
				&& allRows[i]["TAX_RATE"] != "") {
			allRows[i]["H_PRICE_REAL_NOTAX"] = (parseFloat(allRows[i]["H_PRICE_REAL"]
					/ (allRows[i]["TAX_RATE"] * 1000 + 1000) * 1000))
					.toFixed(fixno); // 单品不含税价
		}
		allRows[i]["H_PRICE_REAL"] = (parseFloat(allRows[i]["H_PRICE"]
				* allRows[i]["H_DISCOUNT"])).toFixed(fixno); // 单品实价
		$('#' + prefix + "_addItemDatagrid").datagrid('beginEdit', i);
		$('#' + prefix + "_addItemDatagrid").datagrid('endEdit', i);
	}
}

/*******************************************************************************
 * 数组最大值
 */
Array.min = function(array) {
	return Math.min.apply(Math, array);
}

/*******************************************************************************
 * 数组最小值
 */
Array.max = function(array) {
	return Math.max.apply(Math, array);
}

/*******************************************************************************
 * 明细计算包册数计算包册数 hid:商品名称 amount：商品数量 hPackAgeaPrice：商品对应的件册数
 * 
 * @param hid
 * @param amount
 * @return
 */
function fx_calcuPackNum(hid, amount, hPackAgeaPrice) {
	var packNum;
	if (amount == null || amount == 0) { // 发货数为空
		return '无';
	}
	if (hPackAgeaPrice == null || hPackAgeaPrice == 0) { // 件册数
		return '无';
	}
	packNum = Math.abs(amount) / hPackAgeaPrice;
	if (packNum == 0) {
		return '0+0(' + hPackAgeaPrice + ')';
	} else {
		if ((packNum - Math.floor(packNum)) == 0) {
			return packNum + '+0(' + hPackAgeaPrice + ')';
		} else {
			return Math.abs(Math.floor(packNum)) + "+"
					+ Math.abs(amount - (Math.floor(packNum) * hPackAgeaPrice))
					+ "(" + hPackAgeaPrice + ")";
		}
	}
}

/*******************************************************************************
 * 数量改变的时候计算码洋和实洋
 * 
 * @param obj
 * @return
 */
function fx_codeMoney(obj) {
	if ($(obj).attr("chan") != "T") {
		return;
	}
	var amount = $(obj).val() == "" ? 0 : $(obj).val();
	var curDiv = $("div[realdsid][prefix][dsid]"); // 获取datagrid的div
	var currentRow = $(curDiv).datagrid("getEditRow"); // 获取正在编辑的行
	var i = $(curDiv).datagrid("getRowIndex", currentRow);
	currentRow["H_AMOUNT"] = amount; // 因为数量是可编辑的框，所以此处必须显示赋值，否则
										// 计算通用的明细统计的计算方法中使用的数量有可能是上一次的值
	currentRow["TOTAL_MONEY_ITEM"] = (parseFloat(amount * currentRow["H_PRICE"]))
			.toFixed(fixno); // 码洋
	if (currentRow["H_DISCOUNT"] != null && currentRow["H_DISCOUNT"] != ""
			&& currentRow["H_DISCOUNT"] != "null") {
		currentRow["REAL_MONEY_ITEM"] = (parseFloat(amount
				* currentRow["H_PRICE"] * currentRow["H_DISCOUNT"]))
				.toFixed(fixno); // 实洋
	} else {
		currentRow["REAL_MONEY_ITEM"] = 0;
	}
	var packnum = fx_calcuPackNum(currentRow["H_ID"], amount,
			currentRow["H_PACKAGE_PIECE"]);
	currentRow["PACKNUM"] = packnum;
	$($(curDiv).datagrid('getCellObj', {
		"index" : i,
		"colnName" : "TOTAL_MONEY_ITEM"
	})).text(Number(currentRow["TOTAL_MONEY_ITEM"])); // 码洋
	$($(curDiv).datagrid('getCellObj', {
		"index" : i,
		"colnName" : "REAL_MONEY_ITEM"
	})).text(Number(currentRow["REAL_MONEY_ITEM"]));// 实洋
	$($(curDiv).datagrid('getCellObj', {
		"index" : i,
		"colnName" : "PACKNUM"
	})).text(currentRow["PACKNUM"]); // 包册数
	// 明细中合计
	var divName = $(curDiv).attr("id");
	commonMxTotalCalcu("01110", divName);
}

/*******************************************************************************
 * 数量改变:计算税金、不含税率、含税金额
 * 
 * @param obj
 * @return
 */
function cw_getMoreMoney(obj) {
	if ($(obj).attr("chan") != "T") {
		return;
	}
	var amount = $(obj).val() == "" ? 0 : $(obj).val();
	var curDiv = $("div[realdsid][prefix][dsid]"); // 获取datagrid的div
	var currentRow = $(curDiv).datagrid("getEditRow"); // 获取正在编辑的行
	var i = $(curDiv).datagrid("getRowIndex", currentRow);
	
	currentRow["H_AMOUNT"] = amount; // 数量
	
	currentRow["MX_HMONEY"] = (parseFloat(amount * currentRow["PRICE"]))
			.toFixed(fixno); // 含税金额
	
	currentRow["TAXMONEY"] = ((parseFloat(amount * currentRow["PRICE"]))-
			(parseFloat(amount * currentRow["PRICE"]/1.17))).toFixed(fixno); // 税金
	
	currentRow["MX_BHMONEY"] =(parseFloat(amount * currentRow["PRICE"]/1.17))
	.toFixed(fixno);  // 不含税金额
	
	var currentRow = $(curDiv).datagrid("getRows"); // 获取正在编辑的行
	var total1 = 0;
	var total2 = 0;
	var total3 = 0;
	var total4 = 0;
	
	for ( var i = 0; i < currentRow.length; i++) {
		
		total1 += (currentRow[i]['H_AMOUNT'] == ""
				|| currentRow[i]['H_AMOUNT'] == null
				|| currentRow[i]['H_AMOUNT'] == undefined ? 0
				: parseFloat(currentRow[i]['H_AMOUNT']));
		
		total2 += (currentRow[i]['MX_HMONEY'] == ""
				|| currentRow[i]['MX_HMONEY'] == null
				|| currentRow[i]['MX_HMONEY'] == undefined ? 0
				: parseFloat(currentRow[i]['MX_HMONEY']));
		
		total3 += (currentRow[i]['MX_BHMONEY'] == ""
				|| currentRow[i]['MX_BHMONEY'] == null
				|| currentRow[i]['MX_BHMONEY'] == undefined ? 0
				: parseFloat(currentRow[i]['MX_BHMONEY']));
		
		total4 += (currentRow[i]['TAXMONEY'] == ""
			|| currentRow[i]['TAXMONEY'] == null
			|| currentRow[i]['TAXMONEY'] == undefined ? 0
			: parseFloat(currentRow[i]['TAXMONEY']));
	}

	var curForm = $("form[id][dsid][flag][sflag][pre]");
	
	$(curForm).find('input[qucln=TOTAL_AMOUNT]').val(parseFloat(total1).toFixed(2));
	$(curForm).find('input[qucln=TOTAL_AMOUNT]').attr("chan", "T");
	$(curForm).find('input[qucln=TOTAL_AMOUNT]').next().val(parseFloat(total1).toFixed(2));

	
	$(curForm).find('input[qucln=MX_HMONEYSUM]').val(
			parseFloat(total2).toFixed(2));
	$(curForm).find('input[qucln=MX_HMONEYSUM]').attr("chan", "T");
	$(curForm).find('input[qucln=MX_HMONEYSUM]').next().val(
			parseFloat(total2).toFixed(2));

	$(curForm).find('input[qucln=MX_BHMONEYSUM]').val(
			parseFloat(total3).toFixed(2));
	$(curForm).find('input[qucln=MX_BHMONEYSUM]').attr("chan", "T");
	$(curForm).find('input[qucln=MX_BHMONEYSUM]').next().val(
			parseFloat(total3).toFixed(2));

	$(curForm).find('input[qucln=TAXMONEY]').val(
			parseFloat(total4).toFixed(2));
	$(curForm).find('input[qucln=TAXMONEY]').attr("chan", "T");
	$(curForm).find('input[qucln=TAXMONEY]').next().val(
			parseFloat(total4).toFixed(2));
	
	var divName = $(curDiv).attr("id");
	commonMxTotalCalcu("00100", divName);
}

// 折扣发生改变的时候计算实洋,单品实价
function fx_realMoney(obj) {
	if ($(obj).attr("chan") != "T") {
		return;
	}
	var discount = $(obj).val();
	var curDiv = $("div[realdsid][prefix][dsid]"); // 获取datagrid的div
	var currentRow = $(curDiv).datagrid("getEditRow"); // 获取正在编辑的行
	var i = $(curDiv).datagrid("getRowIndex", currentRow);
	currentRow["H_DISCOUNT"] = discount; // 因为折扣是可编辑的框，所以此处必须显示赋值，否则
											// 计算通用的明细统计的计算方法中使用的数量有可能是上一次的值
	if (discount != null || discount != "" || discount != "null") {
		currentRow["H_PRICE_REAL"] = (parseFloat(currentRow["H_PRICE"]
				* discount)).toFixed(fixno); // 单品实价
		if (currentRow["TAX_RATE"] != undefined
				&& currentRow["TAX_RATE"] != null
				&& currentRow["TAX_RATE"] != ""
				&& currentRow["H_PRICE_REAL"] != undefined
				&& currentRow["H_PRICE_REAL"] != null
				&& currentRow["H_PRICE_REAL"] != "") {
			currentRow["H_PRICE_REAL_NOTAX"] = (parseFloat(currentRow["H_PRICE_REAL"]
					/ (currentRow["TAX_RATE"] * 1000 + 1000) * 1000))
					.toFixed(fixno); // 单品不含税价
		}
		currentRow["REAL_MONEY_ITEM"] = (parseFloat(currentRow["H_AMOUNT"]
				* currentRow["H_PRICE"] * discount)).toFixed(fixno); // 实洋
	} else {
		currentRow["REAL_MONEY_ITEM"] = 0;
	}
	$($(curDiv).datagrid('getCellObj', {
		"index" : i,
		"colnName" : "REAL_MONEY_ITEM"
	})).text(Number(currentRow["REAL_MONEY_ITEM"]));// 实洋
	$($(curDiv).datagrid('getCellObj', {
		"index" : i,
		"colnName" : "H_PRICE_REAL_NOTAX"
	})).text(Number(currentRow["H_PRICE_REAL_NOTAX"])); // 单品不含税价
	// 明细中合计
	var divName = $(curDiv).attr("id");
	commonMxTotalCalcu("00100", divName);
}

/*******************************************************************************
 * 通用的明细行的计算（主要是批量的时候用到）
 * 
 * @return
 */
function commonMxRowCalcu(gridName, index) {
	var currentRow = $("#" + gridName).datagrid('getRow', index);
	// 获取 定价，数量， 折扣，实洋 ，码洋，包册数
	currentRow["TOTAL_MONEY_ITEM"] = (parseFloat((currentRow["H_AMOUNT"] == null ? 0
			: currentRow["H_AMOUNT"])
			* currentRow["H_PRICE"])).toFixed(fixno); // 码洋
	if (currentRow["H_DISCOUNT"] != null && currentRow["H_DISCOUNT"] != ""
			&& currentRow["H_DISCOUNT"] != "null") {
		currentRow["REAL_MONEY_ITEM"] = (parseFloat((currentRow["H_AMOUNT"] == null ? 0
				: currentRow["H_AMOUNT"])
				* currentRow["H_PRICE"] * currentRow["H_DISCOUNT"]))
				.toFixed(fixno); // 实洋

        currentRow["H_PRICE_REAL"] = (parseFloat(
        	currentRow["H_PRICE"]
			* currentRow["H_DISCOUNT"]))
            .toFixed(fixno); // 实价
	} else {
		currentRow["REAL_MONEY_ITEM"] = 0;
	}
	// var packnum =
	// fx_calcuPackNum(currentRow["H_ID"],(currentRow["H_AMOUNT"]==null?0:currentRow["H_AMOUNT"]),currentRow["H_PACKAGE_PIECE"]);
	// currentRow["PACKNUM"]=packnum;
	$($("#" + gridName).datagrid('getCellObj', {
		"index" : index,
		"colnName" : "TOTAL_MONEY_ITEM"
	})).text(Number(currentRow["TOTAL_MONEY_ITEM"])); // 码洋
	$($("#" + gridName).datagrid('getCellObj', {
		"index" : index,
		"colnName" : "REAL_MONEY_ITEM"
	})).text(Number(currentRow["REAL_MONEY_ITEM"]));// 实洋

    $($("#" + gridName).datagrid('getCellObj', {
        "index" : index,
        "colnName" : "H_PRICE_REAL"
    })).text(Number(currentRow["H_PRICE_REAL"]));	// 实价
	// $($("#"+gridName).datagrid('getCellObj',
	// {"index":index,"colnName":"PACKNUM"})).text(currentRow["PACKNUM"]); //包册数
}

/*******************************************************************************
 * 通用的明细统计的计算方法
 */
function commonMxTotalCalcu(params, gridName) {
	var prefix = $('#' + gridName).attr('prefix');
	var allRows = $('#' + gridName).datagrid('getRows');
	var totalPinZhong = 0; // 总品种
	var totalAmount = 0; // 总数量
	var totalRealMoney = 0; // 总实洋
	var totalMoney = 0; // 总码洋
	var totalPackNum = 0; // 总包册数

	var lsPackNum = 0; // 剩余的件包数
	var isbnObj = {};
	var hPackprices = new Array();

	var pzFlag = params.substring(0, 1);
	var taFlag = params.substring(1, 2);
	var trmFlag = params.substring(2, 3);
	var tmFlag = params.substring(3, 4);
	var tpkFlag = params.substring(4, 5);
	var jpkIndex = 0;
	var strDiv = "";
	for ( var i = 0, len = allRows.length; i < len; i++) {
		if (pzFlag == "1") {
			if (isbnObj[allRows[i]["H_ID"]] == 1) {
			} else {
				isbnObj[allRows[i]["H_ID"]] = 1;
				totalPinZhong++;
			}
		}
		if (taFlag == "1") {
			if (allRows[i]["H_AMOUNT"] != null && allRows[i]["H_AMOUNT"] != '') { // 判断数量是否为空或者为null
				totalAmount = parseInt(totalAmount)
						+ Math.abs(parseInt(allRows[i]["H_AMOUNT"])); // footer行的数量累计+添加行的数量
			}
		}
		if (tmFlag == "1") {
			if (allRows[i]["TOTAL_MONEY_ITEM"] != null
					&& allRows[i]["TOTAL_MONEY_ITEM"] != '') { // 判断总码洋是否为空或者为null
				totalMoney = parseFloat(totalMoney)
						+ parseFloat(allRows[i]["TOTAL_MONEY_ITEM"]); // footer行的数量累计+添加行的数量
				totalMoney = (parseFloat(totalMoney)).toFixed(2);
			}
		}
		if (trmFlag == "1") {
			if (allRows[i]["REAL_MONEY_ITEM"] != null
					&& allRows[i]["REAL_MONEY_ITEM"] != '') { // 判断总实洋是否为空或者为null
				totalRealMoney = parseFloat(totalRealMoney)
						+ parseFloat(allRows[i]["REAL_MONEY_ITEM"]); // footer行的实洋累计+添加行的实洋
				totalRealMoney = (parseFloat(totalRealMoney)).toFixed(2);
			}
		}
		if (tpkFlag == "1") {
			if (allRows[i]["PACKNUM"] != null && allRows[i]["PACKNUM"] != ''
					&& allRows[i]["PACKNUM"] != "无"
					&& allRows[i]["PACKNUM"] != "0") {
				if (!isNaN(Number(allRows[i]["H_PACKAGE_PIECE"]))) { // 判断简报书
					hPackprices[jpkIndex] = Number(allRows[i]["H_PACKAGE_PIECE"]); // 件包数
					jpkIndex = Number(jpkIndex) + 1;
				}
				// 获取第一个加好
				var index1 = allRows[i]["PACKNUM"].indexOf("+");
				// 获取第一个左括号
				var index2 = allRows[i]["PACKNUM"].indexOf("(");
				totalPackNum = parseInt(totalPackNum)
						+ parseInt(allRows[i]["PACKNUM"].substring(0, index1));
				lsPackNum = Number(lsPackNum)
						+ Number(allRows[i]["PACKNUM"].substring(index1 + 1,
								index2));
			}
		}
	}
	var strDiv = "";
	if (pzFlag == "1") {
		$("span[id=totalKinds]").text(totalPinZhong);
	}
	if (taFlag == "1") {
		$("span[id=totalAmount]").text(totalAmount);
	}
	if (tmFlag == "1") {
		$("span[id=totalMoney]").text(totalMoney);
	}
	if (trmFlag == "1") {
		$("span[id=totalRealMoney]").text(totalRealMoney);
	}
	if (tpkFlag == '1') {
		var minHpackPrice = Array.min(hPackprices);
		totalPackNum = Math.ceil(Number(lsPackNum) / Number(minHpackPrice))
				+ totalPackNum;
		$("span[id=totalPackNum]").text(totalPackNum);
	}
}

/*******************************************************************************
 * 初始化明细界面的界面 调用的方法
 * 
 * @param params
 * @param gridName
 * @return
 */
function initMxTotalCalcu(params, gridName) {
    if(gridName=='lsztwh_addItemDatagrid'){
        return;
    }
	var prefix = $('#' + gridName).attr('prefix');
	var allRows = $('#' + gridName).datagrid('getRows');
	var totalPinZhong = 0; // 总品种
	var totalAmount = 0; // 总数量
	var totalRealMoney = 0; // 总实洋
	var totalMoney = 0; // 总码洋
	var totalPackNum = 0; // 总包册数
	var lsPackNum = 0; // 剩余的件包数
	var isbnObj = {};
	var hPackprices = new Array();

	var pzFlag = params.substring(0, 1);
	var taFlag = params.substring(1, 2);
	var trmFlag = params.substring(2, 3);
	var tmFlag = params.substring(3, 4);
	var tpkFlag = params.substring(4, 5);

	var jpkIndex = 0;
	var strDiv = "";
	for ( var i = 0, len = allRows.length; i < len; i++) {
		if (pzFlag == "1") {
			if (isbnObj[allRows[i]["H_ID"]] == 1) {
			} else {
				isbnObj[allRows[i]["H_ID"]] = 1;
				totalPinZhong++;
			}
		}
		if (taFlag == "1") {
			if (allRows[i]["H_AMOUNT"] != null && allRows[i]["H_AMOUNT"] != '') { // 判断数量是否为空或者为null
				totalAmount = parseInt(totalAmount)
						+ Math.abs(parseInt(allRows[i]["H_AMOUNT"])); // footer行的数量累计+添加行的数量
			}
		}
		if (tmFlag == "1") {
			if (allRows[i]["TOTAL_MONEY_ITEM"] != null
					&& allRows[i]["TOTAL_MONEY_ITEM"] != '') { // 判断总码洋是否为空或者为null
				totalMoney = parseFloat(totalMoney)
						+ parseFloat(allRows[i]["TOTAL_MONEY_ITEM"]); // footer行的数量累计+添加行的数量
				totalMoney = (parseFloat(totalMoney)).toFixed(2);
			}
		}
		if (trmFlag == "1") {
			if (allRows[i]["REAL_MONEY_ITEM"] != null
					&& allRows[i]["REAL_MONEY_ITEM"] != '') { // 判断总实洋是否为空或者为null
				totalRealMoney = parseFloat(totalRealMoney)
						+ parseFloat(allRows[i]["REAL_MONEY_ITEM"]); // footer行的实洋累计+添加行的实洋
				totalRealMoney = (parseFloat(totalRealMoney)).toFixed(2);
			}
		}
		if (tpkFlag == "1") {
			if (allRows[i]["PACKNUM"] != null && allRows[i]["PACKNUM"] != ''
					&& allRows[i]["PACKNUM"] != "无"
					&& allRows[i]["PACKNUM"] != "0") {
				if (!isNaN(Number(allRows[i]["H_PACKAGE_PIECE"]))) { // 判断简报书
					hPackprices[jpkIndex] = Number(allRows[i]["H_PACKAGE_PIECE"]); // 件包数
					jpkIndex = Number(jpkIndex) + 1;
				}
				// 获取第一个加好
				var index1 = allRows[i]["PACKNUM"].indexOf("+");
				// 获取第一个左括号
				var index2 = allRows[i]["PACKNUM"].indexOf("(");
				totalPackNum = parseInt(totalPackNum)
						+ parseInt(allRows[i]["PACKNUM"].substring(0, index1));
				lsPackNum = Number(lsPackNum)
						+ Number(allRows[i]["PACKNUM"].substring(index1 + 1,
								index2));
			}
		}
	}
	var strDiv = "";
	if (pzFlag == "1") {
		strDiv += "<span name='totalKinds' style='font-size: 14px;'>总品种：<span id='totalKinds'>"
				+ totalPinZhong + "</span></span>&nbsp;&nbsp;";
	}
	if (taFlag == "1") {
		strDiv += "<span style='font-size: 14px;margin-left: 50px;'name='totalAmount' >总数量：<span id='totalAmount'>"
				+ totalAmount + "</span></span>&nbsp;&nbsp;";
	}
	if (tmFlag == "1") {
		strDiv += "<span name='totalMoney'  style='font-size: 14px;margin-left: 50px;'>总码洋：<span id='totalMoney'>"
				+ totalMoney + "</span></span>&nbsp;&nbsp;";
	}
	if (trmFlag == "1") {
		strDiv += "<span name='totalRealMoney' style='font-size: 14px;margin-left:50px;'>总实洋：<span id='totalRealMoney'>"
				+ totalRealMoney + "</span></span>&nbsp;&nbsp;";
	}
	if (tpkFlag == '1') {
		var minHpackPrice = Array.min(hPackprices);
		totalPackNum = Math.ceil(Number(lsPackNum) / Number(minHpackPrice))
				+ totalPackNum;
		strDiv += "<span name='totalPackNum'  style='font-size: 14px;margin-left: 50px;'>总包册数：<span id='totalPackNum'>"
				+ totalPackNum + "</span></span>&nbsp;&nbsp;";
	}
	$('#' + prefix + '_totalItem').html(strDiv);
}
